package chatGUI;
import network.*;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;

import javax.swing.*;



public class fenetre extends JFrame {
	
	ChatNI chat;
	private JButton bSend;
	private JLabel lmesssend;
	private JLabel lmessrec; 
	private JTextArea textRec;
	private JTextArea textToSend;
	
	final static int listeningPort = 1234;
	final static int portDest = 4321;
	
	static UdpReceiver testUDPReceiveText; //= new UdpReceiver(portDest);
	public fenetre ()
	{
		
		initComponents();
		testUDPReceiveText = new UdpReceiver(listeningPort, textRec);
		(new Thread(testUDPReceiveText)).start();

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	private void initComponents() {
		
		 // create the components
		lmesssend = new JLabel("Message To Send ");
		textRec = new JTextArea(3,25);
		textRec.setEditable(false);
		lmessrec = new JLabel("received message ");
		textToSend = new JTextArea(3,25);
		bSend = new JButton("Send");
		
		 // configures the JFrame layout using a border layout
		 this.setLayout(new GridLayout(3,2));
		 // places the components in the layout
		 this.add(lmesssend);
		 this.add(new JScrollPane(textToSend));
		 this.add(lmessrec);
         this.add(new JScrollPane(textRec));
         this.add(bSend);
         bSend.addActionListener(new ButtonSendListener());
		 // packs the fenetre: size is calculated
		 // regarding the added components
		 this.pack();
		 // the JFrame is visible now
		 this.setVisible(true);
	}
	
	
	public class ButtonSendListener implements ActionListener  
	{
		public void actionPerformed (ActionEvent e)
		{
			String msg;
			try
			{
				//msg = new BufferedReader(new InputStreamReader(System.in)).readLine();
				msg = textToSend.getText();
				System.out.println(msg);
				(new UdpSender(portDest)).sendText(InetAddress.getLocalHost(),msg, portDest);
			}catch (IOException e1) {
				System.out.println("Impossible d'envoyer le msg");
				e1.printStackTrace();
			}
		}
	}
	
	
	
	public static void main(String[] args) {
	    fenetre f = new fenetre();
	}

}
